<template>
    <div class="root">
        <h1>{{ name }}</h1>
        <h2>{{ age }}</h2>
        <h2 v-if=schoolName>{{ schoolName }}</h2>
        <h2 v-if= nanoid>{{nanoid}}</h2>
        <hr>
        <button @click="touchMe">touchMe</button>
        <button @click="sendNameToSchool">把学生名发给学校</button>
        <button @click="sendIDtoApp">发送id给app</button>
    </div>
</template>

<script>
import Vue from 'vue';
import { nanoid } from "nanoid";
import pubsub from 'pubsub-js'
export default Vue.extend({
    name: 'MyStudent',

    data() {
        return {
            name: "马云",
            age: 55,
            schoolName: null,
            nanoid: null,
        }
    },

    methods: {
        touchMe() {
            this.age += 1
        },
        sendNameToSchool(){
            console.log('getStudentName')
            pubsub.publish('getStudentName',this.name)
        },
        sendIDtoApp(){
            pubsub.publish('getNanoid',nanoid())
        }
    },
    mounted() {
        this.getNanoidBySchoolID = pubsub.subscribe('getNanoidBySchool',(_,nanoID)=>{
            this.nanoid = nanoID
        })
    },
    beforeDestroy(){
        pubsub.unsubscribe(this.getNanoidBySchoolID)
    }


});
</script>


<style lang="less" scoped>
    .root {
        background-color: rgb(140, 90, 15);
    }
</style>